//发送消息
function sendmsg(){
	var msg = $("#msgbody").html();
	if(msg==''||msg=='<div><br></div><div><br></div>'){
		$("#msgbody").html("");
		return layer.msg("说点什么吧!");
	}
	websocket.send(msg);
	setMessageInnerHTMLSel(msg);
	$("#msgbody").html("");
	scrollbottom();
}

//将消息显示在网页上(0上线/1下线/2消息)
function setMessageInnerHTML(obj) {
		//console.log(obj);
	var msgEntity = $.parseJSON(obj);
	var msg = msgEntity.msg;
	if(msgEntity.type==10){
		msg = '<div class="sysmsg">'+msgEntity.msg+msgEntity.sendtime+'</div><br>';
		adduser(msgEntity.userId,msgEntity.avatar,msgEntity.loginName);
	}else if(msgEntity.type==11){
		msg = '<div class="sysmsg">'+msgEntity.msg+msgEntity.sendtime+'</div><br>';
		removeuser(msgEntity.userId);
	}else if(msgEntity.type==12){
		inituser(msgEntity.users);
		msg='<div class="sysmsg">你已成功加入聊天室'+msgEntity.sendtime+'</div><br>';
	}else if(msgEntity.type==2){
		msg='<div class="sysmsg">'+msgEntity.sendtime+'</div><div class="item left"><img class="header-img hand" title="'+msgEntity.loginName+'" onclick="userinfo(this)" value="'+msgEntity.avatar+'" src="'+msgEntity.avatar+'" /><span class="message">'+msg+'</span></div>'
		}
        $("#msgpanel").append(msg);
    }


//关闭连接
function closeWebSocket() {
    websocket.close();
}

//滚动到底部
function scrollbottom(){
	var msgpanel = document.getElementById('msgpanel');
	msgpanel.scrollTop = msgpanel.scrollHeight;
}

function userinfo(obj){
	layer.open({
		  type: 1,
		  title: false,
		  closeBtn: 0,
		  skin: 'layui-layer-nobg', //没有背景色
		  offset: ['38%', '38%'],//设置位移
		  shadeClose: true,
		  content: '<img height="350" width="350" src="'+$(obj).attr("value")+'" title="微信赞助"/>'
	});
}

function cleanmsg(){
	layer.confirm('清空后无法恢复!确定要清空全部吗？', {
		btn : [ '确定', '取消' ]
	}, function() {
		$("#msgpanel").empty();
		layer.msg("已清空");
		layer.closeAll(this);
	}) 
}

function alerticon(){
	layer.tips(icon, '#icon', {
		  tips: 1
		});
}

function selecticon(obj){
	var msg = '<img src="'+$(obj).attr("src")+'">';
	$("#msgbody").append(msg);
}

function inituser(obj){
	for(var i=0; i<obj.length; i++){
		console.log(obj[i].loginName);
		$("#usersli").append('<li id="user'+obj[i].userId+'"><img class="header-img" alt="" src="'+obj[i].avatar+'"><a>'+obj[i].loginName+'</a></li>');
	}
}

//上线添加用户
function adduser(userid,avatar,username){
	$("#usersli").append('<li id="user'+userid+'"><img class="header-img" alt="" src="'+avatar+'">'+username+'</li>');
}

//下线移除
function removeuser(userid){
	$("#user"+userid).remove();
}